package com.fengmi.job;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fengmi.miaosha.entity.MsGoods;
import com.fengmi.miaosha.service.IMsGoodsService;
import com.fengmi.utils.date.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

//@Component
public class MiaoshaJob {


    @Autowired
    private IMsGoodsService goodsService;


    @Autowired
    private StringRedisTemplate redisTemplate;


    //@Scheduled(cron = "0 0 0/2 * * ?")
    @Scheduled(cron = "0 * * * * ?")
    public void miaoshaMysql2Redis(){

        //获取当前时间的最近的5个时间区间
        List<Date> dateMenus = DateUtil.getDateMenus();

        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        SimpleDateFormat sfh = new SimpleDateFormat("yyyyMMddHH");

        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps("menhu:miaosha:goods");


        dateMenus.forEach(date -> {

            String start = sf.format(date);

            Date endDate = DateUtil.addDateHour(date, 2);
            String end = sf.format(endDate);

            //获取每个时间区间的商品列表（审核、秒杀库存大于0 ）
            QueryWrapper<MsGoods> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("seckill_status","1");
            queryWrapper.gt("seckill_count",0);
            queryWrapper.ge("seckill_starttime",start);
            queryWrapper.le("seckill_endtime",end);


            List<MsGoods> list = goodsService.list(queryWrapper);

            String field = sfh.format(date);   //2022031718
            if(list!=null || list.size() > 0){
                //存放到Redis
                operations.put(field, JSONUtil.toJsonStr(list));
            }

        });


    }
}
